'use strict'

const sha1 = require('sha1')
const getRawBody = require('raw-body')
const Wechat = require('./wechat')
const utils = require('../libs/utils/xml')

module.exports = function(opts){
    var wechat = new Wechat(opts)
    console.log('jinlaile')
    
    return function async (ctx,next) {
        const token = opts.token
        console.log(ctx)
        var signature = ctx.query.signature
        var nonce = ctx.query.nonce
        var timestamp = ctx.query.timestamp
        var echostr = ctx.query.echostr

        var str = [token,timestamp,nonce].sort().join("")
        var sha = sha1(str)

        if (sha == signature){
            ctx.body = echostr + ''
        }else{
            ctx.body = 'wrong'
        }
        if(ctx.methods === 'POST'){
            const data = getRawBody(ctx.req,{
                length:ctx.length,
                limit:'1mb',
                encoding:ctx.charset
            })
            console.log(data)

            const content = utils.parseXMLAsync(data)
            console.log(content)
        }


        //next()
    }
}